﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Alignmentizer
{
	static class HelperFunctions
	{

		/// <summary>
		/// Gets a number from the user via command line. Returns null if no number is entered
		/// </summary>
		/// <returns></returns>
		public static Nullable<int> GetNumericInput()
		{
			string input;
			int result;

			while (true)
			{
				input = Console.ReadLine();
				if (input == "")
					return null;
				else if (int.TryParse(input, out result))
					return result;
				else
					Console.Write("Must be a number! Try again: ");
			}

		}

		/// <summary>
		/// Reads in multiple sequences from the passed file name. Returns an array of strings containing the sequences
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		public static string[] ImportSequence(string filename, int numSequences)
		{
			string[] sequences = new string[numSequences];

			System.IO.StreamReader sr = new System.IO.StreamReader(filename);

			for (int i = 0; i < numSequences; i++)
				sequences[i] = sr.ReadLine();
			
			return sequences;
		}

		/// <summary>
		/// Imports a scoring matrix from a file. This is stored as a dictionary with the letter pairs as the key and their score as the value
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		public static Dictionary<string, int> ImportScoringMatrix(string filename)
		{
			Dictionary<string, int> result = new Dictionary<string, int>();
			System.IO.StreamReader sr = new System.IO.StreamReader(filename);
			
			/*alright so the format for this thang is going to be like so:
			 * Order of letters: A	R	N	D	C	Q	E	G	H 	I	L	K	M	F	P	S	T 	W	Y	V 
			 * First row contains score of A aligned with A
			 * Second row contains score of R aligned with A [tab] R aligned with R
			 * Third row contains score of N aligned with A [tab] N aligned with R [tab] N aligned with N
			 * and so on...
			 * */
			string elementOrder = "ARNDCQEGHILKMFPSTWYV";

			for (int i = 0; i < elementOrder.Length; i++)
			{
				string line = sr.ReadLine();
				string[] splitLine;
				//values are separated by tabs
				splitLine = line.Split('\t');

				for (int j = 0; j < splitLine.Length; j++)
				{
					//Omg everything about this section feels SSOOO wrong but well here we are
					string keyValue = "";
					keyValue += elementOrder[i];
					keyValue += elementOrder[j];
					int value;
					int.TryParse(splitLine[j], out value);
					result.Add(keyValue, value);
				}

				
			}
			return result;
		}

	}
}
